﻿#ifndef __LUA_OBJ_H__
#define __LUA_OBJ_H__

#include "./refobj.h"
#include "./luawrapper.h"

#define NULL_OBJECT -1

class LuaObj
{
public:
    LuaObj();
    ~LuaObj();

	template <class T>
	void InitObj(T* pObj)
	{
		lua_State* luaState = LuaEx::GetInstance().GetLuaState();
		string strMetaName = Wrapper<T*>::GetObjectType();

		T** ppWrapper = (T**)lua_newuserdata(luaState, sizeof(T*));
		*ppWrapper = NULL;

		luaL_getmetatable(luaState, strMetaName.c_str());

		if (!lua_istable(luaState, -1))
		{
			lua_pop(luaState, 1);
			return;
		}

		lua_setmetatable(luaState, -2);

		*ppWrapper = pObj;

		m_addr = luaL_ref(luaState, LUA_REGISTRYINDEX);
		//AddRef
	}

	void InitObj(int addr);
    void CloneObj(int addr);
    int GetObj();
	void PushObj(lua_State* luaState);

private:
	CRITICAL_SECTION m_csThreadSafe;

    int m_addr;
	lua_State* m_luaState;
};

typedef RefObj<LuaObj> luaobj;

#endif